//
//  AppDelegate.m
//  shopSN
//
//  Created by yisu on 16/6/12.
//  Copyright © 2016年 yisu. All rights reserved.
//

#import "AppDelegate.h"
#import "ZWelcomeViewController.h"
#import "ZTabBarViewController.h"//主控制器
#import "WXApi.h"

#import "UMSocial.h"
#import "UMSocialWechatHandler.h"
//#import "UMSocialSinaSSOHandler.h"
#import "UMSocialQQHandler.h"
#import "UPPaymentControl.h"


//test
#import "TestViewController.h"
@interface AppDelegate ()<WXApiDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    //创建 window
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];

    //页面 代码如下
    NSUserDefaults *ud = [NSUserDefaults  standardUserDefaults];
    BOOL isVisibled = [ud boolForKey:@"isVisibled"];
    if (!isVisibled) {
        ZWelcomeViewController *vc = [[ZWelcomeViewController alloc] init];
        BaseNavigationController *navi = [[BaseNavigationController alloc] initWithRootViewController:vc];
        self.window.rootViewController = navi;
        
        
    }else{
        //创建 tabBar
        ZTabBarViewController *tabBarVc = [[ZTabBarViewController alloc] init];
        
        //设置 窗口的rootViewController
        self.window.rootViewController = tabBarVc;
    }
    
    
    
    //显示窗口
    [self.window makeKeyAndVisible];
    
    
    //微信
    //1.微信测试APPID wxb4ba3c02aa476ea1
    //2.设置微信APPID为URL Schemes
    //3.导入微信支付依赖的类库。发起支付，调起微信支付
    //4.处理支付结果
    
    [WXApi registerApp:WXId withDescription:WXDescription];
    
    //友盟分享

    [UMSocialData setAppKey:UMKey];
    
     // 设置微信AppId、appSecret，分享url
    [UMSocialWechatHandler setWXAppId:WXId appSecret:WXScerect url:RootURL];
    
    // 设置QQAppId、appSecret，分享url
    [UMSocialQQHandler setQQWithAppId:QQId appKey:QQKey url:RootURL];
    
    
    //对未安装客户端平台进行隐藏
//    [UMSocialConfig hiddenNotInstallPlatforms:@[UMShareToQQ, UMShareToQzone, UMShareToWechatSession, UMShareToWechatTimeline]];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - WXApiDelegate
- (void)onResp:(BaseResp *)resp {
    
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去微信服务器端查询
        NSString *strMsg,*strTitle = [NSString stringWithFormat:@"支付结果"];
        
        switch (resp.errCode) {
            case WXSuccess:
                strMsg = @"支付结果：成功！";
                NSLog(@"支付成功－PaySuccess，retcode = %d", resp.errCode);
                break;
                
            default:
                strMsg = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                NSLog(@"错误，retcode = %d, retstr = %@", resp.errCode,resp.errStr);
                break;
        }
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        
    }
    
    
}


-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    return [WXApi handleOpenURL:url delegate:self];
    
    return  [UMSocialSnsService handleOpenURL:url];
}


#pragma mark *** huidiao ***
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    
    
    [[UPPaymentControl defaultControl] handlePaymentResult:url
                                             completeBlock:^(NSString *code, NSDictionary *data) {
                                                 
                                                 //结果code为成功时，先校验签名，校验成功后做后续处理
                                                 if([code isEqualToString:@"success"]) {
                                                     
                                                     //判断签名数据是否存在
                                                     if(data == nil){
                                                         //如果没有签名数据，建议商户app后台查询交易结果
                                                         return;
                                                     }
                                                     
                                                     //数据从NSDictionary转换为NSString
                                                     NSData *signData = [NSJSONSerialization dataWithJSONObject:data
                                                                                                        options:0
                                                                                                          error:nil];
                                                     NSString *sign = [[NSString alloc] initWithData:signData
                                                                                            encoding:NSUTF8StringEncoding];
                                                     
                                                     NSLog(@"Sign: %@", sign);
                                                     
                                                     //验签证书同后台验签证书
                                                     //此处的verify，商户需送去商户后台做验签
                                                     //支付成功且验签成功，展示支付成功提示
                                                     //验签失败，交易结果数据被篡改，商户app后台查询交易结果
                                                     
                                                 } else if([code isEqualToString:@"fail"]) {
                                                     //交易失败
                                                 } else if([code isEqualToString:@"cancel"]) {
                                                     //交易取消
                                                 }
                                             }];
    
    

    BOOL result = [UMSocialSnsService handleOpenURL:url];
    if (result == FALSE) {
        //调用其他SDK，例如支付宝SDK等
        if ([sourceApplication isEqualToString:@"com.tencent.xin"]) {
            //微信支付回调
            return [WXApi handleOpenURL:url delegate:self];
        }
        
        if ([url.host isEqualToString:@"safepay"]) {
            //跳转支付宝钱包进行支付，处理支付结果
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
                NSLog(@"result = %@",resultDic);
            }];
        }
        return YES;
        
    }


    return result;

}


// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{

    [[UPPaymentControl defaultControl] handlePaymentResult:url
                                             completeBlock:^(NSString *code, NSDictionary *data) {

                                                 //结果code为成功时，先校验签名，校验成功后做后续处理
                                                 if([code isEqualToString:@"success"]) {

                                                     //判断签名数据是否存在
                                                     if(data == nil){
                                                         //如果没有签名数据，建议商户app后台查询交易结果
                                                         return;
                                                     }

                                                     //数据从NSDictionary转换为NSString
                                                     NSData *signData = [NSJSONSerialization dataWithJSONObject:data
                                                                                                        options:0
                                                                                                          error:nil];
                                                     NSString *sign = [[NSString alloc] initWithData:signData
                                                                                            encoding:NSUTF8StringEncoding];

                                                     NSLog(@"Sign: %@", sign);

                                                     //验签证书同后台验签证书
                                                     //此处的verify，商户需送去商户后台做验签
                                                     //支付成功且验签成功，展示支付成功提示
                                                     //验签失败，交易结果数据被篡改，商户app后台查询交易结果

                                                 } else if([code isEqualToString:@"fail"]) {
                                                     //交易失败
                                                 } else if([code isEqualToString:@"cancel"]) {
                                                     //交易取消
                                                 }
                                             }];

    BOOL result = [UMSocialSnsService handleOpenURL:url];
    if (result == FALSE) {
        //调用其他SDK，例如支付宝SDK等
        if ([url.host isEqualToString:@"com.tencent.xin"]) {
            //微信支付回调
            return [WXApi handleOpenURL:url delegate:self];
        }

        if ([url.host isEqualToString:@"safepay"]) {
            //跳转支付宝钱包进行支付，处理支付结果
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
                NSLog(@"result = %@",resultDic);
            }];
        }
        return YES;
        
    }
    
    
    
    return result;
    
   
}







@end
